
import defaultSetting from "./defaultSetting";
import {toRaw} from "vue";
const shareds = {

  /**
   * @description: 获取缓存姓名
   * @param {String} name
   * @return {*}
   */
  getStorageName: (name) => {
    return `${defaultSetting.from}_${defaultSetting.name}_${name}`;
  },
  /**
   * @description: 获取存储
   * @param {String}name 存储变量名
   * @param {Boolean} isCache 是否非持久存储
   * @return {*} info 存储的内容
   */
  getStorage: (name, isCache) => {
    const storageName = shareds.getStorageName(name);
    let info = null;
    if (isCache) {
      info = sessionStorage.getItem(storageName);
    } else {
      info = localStorage.getItem(storageName);
    }
    return info;
  },

  /**
   * @description: 清空存储
   * @param {Boolean} isCache 是否是清空持久存储
   */
  clearStorage: (isCache) => {
    if (isCache) {
      sessionStorage.clear();
    } else {
      localStorage.clear();
    }
  },

  /**
   * @description: 打印数据
   * @param {*} msg 可选 打印的变量
   * @param {String}title  可选 打印的title
   */
  consoleInfo: (msg = "", title = "") => {
    console.group(
      `%c${new Date().toLocaleTimeString()} 【主应用-${defaultSetting.name}】`,
      `color:${defaultSetting.primaryColor};font-weight: bold;`
    );
    console.log(`${title} -- `, toRaw(msg));
    console.groupEnd();
  },
  clearCookie: (name) => {
    let d = new Date();
    d.setTime(-1);
    let expires = "expires=" + d.toUTCString();
    document.cookie = name + "=''; " + expires;
  },

  /**
   * @description: 设置存储
   * @param {String}name 存储变量名
   * @param {*}info 存储内容
   * @param {Boolean} isCache 是否非持久存储
   */
  setStorage: (name, info, isCache) => {
    return new Promise((resolve) => {
      const storageName = shareds.getStorageName(name);
      if (isCache) {
        // sessionStorage 会话级别存储
        sessionStorage.setItem(storageName, info);
      } else {
        localStorage.setItem(storageName, info);
      }
      resolve();
    });
  },

  /**
   * @description: 判断当前是否是手机端
   */
  isMobile: () => {
    const mobile = navigator.userAgent.match(
      /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
    );
    return mobile ? true : false;
  },

  getQueryObj: (queryString) => {
    let queryParams = {};
    let queryArr = queryString.split("&");
    for (let item of queryArr) {
      const res = item.split("=");
      queryParams[res[0]] = res[1];
    }
    return queryParams;
  },

  objectToQueryString: (obj) => {
    const keyValuePairs = [];
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        keyValuePairs.push(key + '=' + obj[key]);
      }
    }
    return keyValuePairs.join('&');
  }
}


export default shareds;